package com.woniuxy.amusementparkos.service.wyh.imp;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.woniuxy.amusementparkos.dao.wyh.WristStrap_RepositoryDao;
import com.woniuxy.amusementparkos.entity.lsy.WristStarp;
import com.woniuxy.amusementparkos.entity.wyh.WristStrap_Repository;
import com.woniuxy.amusementparkos.entity.wyh.WristStrap_msg;
import com.woniuxy.amusementparkos.exception.XlsxException;
import com.woniuxy.amusementparkos.service.wyh.WristStrap_RepositoryService;
/**
 * 腕带仓库service,查询所有腕带、和根据腕带id查询腕带
 * @author wyh
 *
 */
@Service
public class WristStrap_RepositoryServiceImp implements WristStrap_RepositoryService{
	@Autowired
	WristStrap_RepositoryDao wristStrap;
	/*
	 * 根据id查询仓库腕带信息
	 * @param 腕带id
	 */
	@Override
	public WristStrap_Repository getWristStrap(String wriststrap_id) {
		
		return wristStrap.getWristStrap(wriststrap_id);
	}
	/*
	 * 查询所有
	 * @see com.woniuxy.amusementparkos.service.wyh.WristStrap_RepositoryService#selectAll()
	 */
	@Override
	public List<WristStrap_Repository> selectAll() {
		// TODO Auto-generated method stub
		return wristStrap.getAll();
	}
	
	/*
	 * 根据腕带编号、更改腕带状态
	 * @param wriststrp_id 腕带编号 state更改后状态码
	 */
	@Override
	public void updateState(String wriststrp_id, Integer state) {
		
		wristStrap.updateState(wriststrp_id, state);
		
	}
	@Override
	public Integer countWristStrapByType(Integer type_id) {
		return wristStrap.countWristStrapByType(type_id);
	}
	
	//根据腕带编号查询非结算状态的腕带常用信息
	@Override
	public WristStrap_msg getBywriststrp_id(String wriststrp_id) {		
		return wristStrap.getBywriststrp_id(wriststrp_id);
	}
	
	
	
	
	
	
	// ================================================================
	// 以下为Muzi：创建的代码
	@Override
	public List<WristStrap_Repository> selectAllByPageAndLimit(Integer page, Integer limit) {
		// 获得数据的起始序号
		int start = (page-1)*limit;
		return wristStrap.selectAllByPageAndLimit(start,limit);
	}
	
	@Override
	public List<WristStrap_Repository> selectAllByPageAndCondition(String condition, Integer page, Integer limit) {
		// 获得数据的起始序号
		int start = (page-1)*limit;
		// 执行条件查询
		return wristStrap.selectAllByPageAndCondition(condition,start,limit);
	}
	@Override
	public List<WristStrap_Repository> selectAllByPageAndType(Integer type_id, Integer page, Integer limit) {
		// 获得数据的起始序号
		int start = (page-1)*limit;
		return wristStrap.selectAllByPageAndType(type_id,start,limit);
	}
	@Override
	public void insertWristStrap(WristStrap_Repository wristStrap_Repository) {
		// 添加腕带
		wristStrap.insertWristStrap(wristStrap_Repository);
	}
	@Override
	public void deleteWristStrap(String wriststrp_id) {
		// 通过主键删除
		wristStrap.deleteWristStrapByWriststrp_id(wriststrp_id);
	}
	@Override
	public void updateWristStrap(WristStrap_Repository wristStrap_Repository) {
		// 执行修改
		wristStrap.updateWristStrapRepository(wristStrap_Repository);
	}
	@Override
	public Long countWristStrapsByNoCondition() {
		return wristStrap.countWristStrapsByNoCondition();
	}
	@Override
	public Long countWristStrapsByCondition(String condition) {
		return wristStrap.countWristStrapsByCondition(condition);
	}
	@Override
	public Long countByType(Integer type_id) {
		return wristStrap.countByType(type_id);
	}
	@Override
	public List<WristStrap_Repository> selectAllByPageAndConditionAndType(Integer type_id, String condition,
			Integer page, Integer limit) {
		// 获得数据的起始序号
		Integer start = (page-1)*limit;
		return wristStrap.selectAllByPageAndConditionAndType(type_id,condition,start,limit);
	}
	@Override
	public Long countWristStrapsByConditionAndType(String condition, Integer type_id) {
		return wristStrap.countWristStrapsByConditionAndType(condition,type_id);
	}
	@Transactional// 启用事务控制
	@Override
	public  List<WristStarp> batchImport(String fileName, MultipartFile file) throws IOException,RuntimeException{
		boolean notNull = false;
		// 解析表格后的数据容器
        List<WristStarp> wristStarpList = new ArrayList<>();
        // 判断上传的文件格式是否正确
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new XlsxException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        // 定义流
        InputStream is = file.getInputStream();
        // 提高作用域
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        // 三方工具核心对象
        Sheet sheet = wb.getSheetAt(0);
        // 判断非空
        if(sheet!=null){
            notNull = true;
        }
        // 定义实体类
        WristStarp wristStarp;
        // 遍历集合
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            // 定义对象初始化
            wristStarp = new WristStarp();
            // 读取一行的值，设置读取类型
            row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
            // 接收第一列的值
            String wriststrp_id = row.getCell(0).getStringCellValue();
            if(null == wriststrp_id || wriststrp_id.isEmpty()){
                throw new XlsxException("导入失败(第"+(r+1)+"行,印刷号未填写)");
            }
            if(wriststrp_id.length()>5) {
            	throw new XlsxException("导入失败(第"+(r+1)+"行,印刷号长度超过5)");
            }
            // 读取二列的值，定义读取类型
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            // 接收第二列的值
            String type = row.getCell(1).getStringCellValue();
            Integer type_id;
            if(type==null||type.isEmpty()){
                throw new XlsxException("导入失败(第"+(r+1)+"行,不存在类型编号，或未填写)");
            }else {
            	type_id = Integer.parseInt(type);
            }
            row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
            Integer state;
            String stateStr = row.getCell(2).getStringCellValue();
            if(stateStr==null||stateStr.isEmpty()){
                throw new XlsxException("导入失败(第"+(r+1)+"行,不存在状态信息，或未填写)");
            }else {
            	state = Integer.parseInt(stateStr);
            	if(state<0||state>3) {
            		 throw new XlsxException("导入失败(第"+(r+1)+"行,状态信息:"+state+"未定义)");
            	}
            }
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
            String serial_numbers = row.getCell(3).getStringCellValue();
            if(serial_numbers==null || serial_numbers.isEmpty()){
                throw new XlsxException("导入失败(第"+(r+1)+"行,序列号未填写)");
            }
            // 赋值
            wristStarp.setWriststrp_id(wriststrp_id);
            wristStarp.setType_id(type_id);
            wristStarp.setState(state);
            wristStarp.setSerial_numbers(serial_numbers);
            wristStarpList.add(wristStarp);
        }
        int i = 0;
        // 循环添加
        for (WristStarp myData : wristStarpList) {
        	i++;
        	// 循环添加
        	try {
        		// 捕获添加时候的异常
        		wristStrap.insertOneWristStrap(myData);
			} catch(DuplicateKeyException e){
				throw new XlsxException("添加错误，请检查第"+i+"行序列号或印刷号是否已存在于数据库中");
			} catch(DataIntegrityViolationException e){
				throw new XlsxException("添加错误，请检查第"+i+"行数据，可能是腕带类型编号未已启用");
			} catch (Exception e) {
				throw new XlsxException("添加第"+i+"行时发生错误，请检查数据或联系管理员");
			}
        }
        if(notNull) {
        	return wristStarpList;
        }else {
        	return null;
        }
    }
	@Transactional// 启用事务
	@Override
	public void deleteWristStrapList(String[] wriststrp_id) {
		// 循环遍历删除
		for (String id : wriststrp_id) {
			wristStrap.deleteWristStrapByWriststrp_id(id);
		}
		
	}

}


			

